import axios from '../../../plugins/axios'
import { UserActionsEnum } from '../../../_/vue/store/user'
import router from '../../../router'

export default {
  [UserActionsEnum.LOGIN] ({ state }, payload) {
    return axios.post('/login', payload).then(response => {
      state.token = response.data.token
      state.user = response.data
      state.user = { username: response.data.username, avatar: response.data.avatar }
      window.sessionStorage.setItem('token', response.data.token)
      router.push('/')
      return Promise.resolve(response.data)
    }).catch((err) => Promise.reject(err))
  },
  [UserActionsEnum.LOGOUT] ({ state }) {
    return axios.post('/logout').then(response => {
      window.sessionStorage.removeItem('token')
      state.user = {}
      state.token = ''
      router.push('/login')
    })
  },
  [UserActionsEnum.GET_USERINFO] ({ state }) {
    axios.get('/userinfo').then(response => {
      state.user = response.data
    })
  },
  [UserActionsEnum.LIST] ({ state }, payload = {}) {
    return axios.get('/users', { params: payload })
  },
  [UserActionsEnum.INFO] ({ commit }, uuid) {
    return axios.get(`/users/${uuid}`)
  }
}
